package com.stock.dao;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import com.dalin.common.PropertyConst;
import com.dalin.common.utils.NumberUtils;
import com.dalin.common.utils.TextUtils;
import com.dalin.framework.dao.ConnectFactory;
import com.dalin.framework.dao.DbConn;
import com.stock.StockProp;

public class DiaryDataDao {
	public static void update(StockProp stockEntity) {
		try {
			StockProp s0 = StockInfoDao.findStockByCode(stockEntity.getCode());
			DbConn conn = ConnectFactory.getConnectionInstance(JDBC.getJdbc());
			List<Map> dataList = conn.queryData("select * from diary_data where trade_date='"+stockEntity.getDate()+"' and stock_id="+s0.getStockId());
			if (dataList.size() > 0) {
				return;
			}
			StringBuffer sb = new StringBuffer("INSERT INTO diary_data(trade_date,stock_id,open_price,high_price,low_price,volume) VALUES(");
			sb.append("'"+stockEntity.getDate()+"',")
				.append(s0.getStockId()+",")
				.append(stockEntity.getOpen()+",")
				.append(stockEntity.getHigh()+",")
				.append(stockEntity.getLow()+",")
				.append(stockEntity.getVolume()+")");
			System.out.println(sb.toString()+"begin");
			conn.executeUpdate(sb.toString());
			System.out.println(sb.toString()+"over");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static Map queryDiaryData(String code, String date) {
		try {
			StockProp s0 = StockInfoDao.findStockByCode(code);
			DbConn conn = ConnectFactory.getConnectionInstance(JDBC.getJdbc());
			List<Map> dataList = conn.queryData("select * from diary_data where trade_date='"+date+"' and stock_id="+s0.getStockId());
			if (dataList.size() > 0) {
				return dataList.get(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return null;
	}
	public static String getInternetHistoryByCode(String code) {
		String url0 = "http://ichart.yahoo.com/table.csv?s=" + code
				+ (code.startsWith("600") ? ".ss" : ".sz");
		String url1 = "http://table.finance.yahoo.com/table.csv?s=" + code + (code.startsWith("600") ? ".ss" : ".sz");
		String url = url1;
		System.out.println("downloading code-->" + url);
		HttpClient httpClient = new HttpClient();
		HttpMethod method = new GetMethod(url);
		setHeaders(method);
		try {
			System.out.println("getHistoryDataByCode=="+code+"==begin");

			httpClient.executeMethod(method);
			String response = method.getResponseBodyAsString();
			System.out.println("getHistoryDataByCode=="+code+"==end");
			if (response.contains("Sorry, the page you requested was not found")) {
				throw new Exception("error data");
			}
			method.releaseConnection();
			return response;
		} catch (Exception e) {
			try {
				TextUtils.appendToText(code, new File("D:/failed.txt"));
			} catch (Exception e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
		return null;
	}
	
	public static List<String> getStockPool() {
		List<String> rtnList = new ArrayList<String>();
		String initCode = "000001";
		try {
			for (int i = 0; i < 3999; i++) {
				String rtn = getCurrentData(initCode);
				if (rtn != null) {
					String s1 = rtn.split("\"")[1].split(",")[0];
					System.out.println(initCode+"=="+s1);
					rtnList.add(initCode+"=="+s1);
				}
				initCode = NumberUtils.getNextStrNum(initCode);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return rtnList;
	}
	
	public static String getCurrentData(String code) {
		try {
			HttpClient httpClient = new HttpClient();
			String url = "http://hq.sinajs.cn/list="
					+ (code.startsWith("60") ? "sh" : "sz") + code;
			HttpMethodBase method = new PostMethod(url);
			method.setRequestHeader("Content-Type",
					"application/json;charset=UTF-8");
			httpClient.getHttpConnectionManager().getParams()
					.setConnectionTimeout(50000);
			httpClient.executeMethod(method);
			String response = method.getResponseBodyAsString();
			method.releaseConnection();
			if ("\"\";\n".equals(response.split("=")[1])) {
				return null;
			}
			return response;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	private static void setHeaders(HttpMethod method) {
		method.setRequestHeader("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		method.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
		method.setRequestHeader("User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0");
		method.setRequestHeader("Accept-Charset", "gzip, deflate");
		method.setRequestHeader("Connection", "keep-alive");
	}
}
